<template>
  <div class="audit-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>
          {{ isLegalSpecialist ? '法务审核 - 待审核合同' : '财务审核 - 待审核合同' }}
        </h2>
        <button @click="goToDashboard" class="btn btn-secondary">
          <i class="fa fa-home mr-2"></i>返回主页
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 待审核的合同 -->
    <div v-if="!loading && contracts.length > 0" class="card mt-4">
      <div class="card-header bg-warning text-white">
        <h3>待审核的合同</h3>
      </div>
      <div class="card-body">
        <div class="contracts-table overflow-x-auto">
          <table class="table w-full border-collapse" style="table-layout: fixed;">
            <thead class="bg-light">
            <tr>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同ID</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同名称</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">项目经理</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">客户</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">创建时间</th>
              <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="contract in contracts" :key="contract.id" class="border-b border-gray-200 hover:bg-gray-50 transition-colors duration-200">
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.id }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.name }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.projectManagerName }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.customerCompanyName }}</td>
              <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ formatDate(contract.createTime) }}</td>
              <td class="py-3 px-4 border-b border-gray-200">
                <button @click="viewContract(contract.id)" class="btn btn-primary btn-sm">
                  <i class="fa fa-check-circle mr-2"></i>审核合同
                </button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件（含跳转功能） -->
        <div class="pagination mt-3 d-flex justify-content-between flex-wrap gap-2">
          <div>
            每页显示 {{ pageSize }} 条，共 {{ totalCount }} 条
          </div>
          <div class="pagination-controls d-flex align-items-center gap-3">
            <!-- 分页按钮 -->
            <div class="pagination-buttons d-flex align-items-center">
              <button
                  @click="prevPage"
                  :disabled="currentPage === 0"
                  class="btn btn-sm btn-outline-secondary"
              >
                <i class="fa fa-chevron-left"></i> 上一页
              </button>
              <span class="mx-2">
                第 {{ currentPage + 1 }} 页，共 {{ totalPages }} 页
              </span>
              <button
                  @click="nextPage"
                  :disabled="currentPage === totalPages - 1"
                  class="btn btn-sm btn-outline-secondary"
              >
                下一页 <i class="fa fa-chevron-right"></i>
              </button>
            </div>

            <!-- 页面跳转控件 -->
            <div class="page-jump d-flex align-items-center gap-2">
              <span>跳至：</span>
              <input
                  type="number"
                  v-model.number="jumpPageNum"
                  :min="1"
                  :max="totalPages"
                  class="form-control page-input"
                  @keyup.enter="handleJump"
                  placeholder="页码"
              >
              <button
                  @click="handleJump"
                  :disabled="!isJumpValid"
                  class="btn btn-sm btn-jump"
              >
                <i class="fa fa-arrow-right mr-1"></i>确认
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 没有待审核的合同 -->
    <div v-else-if="!loading && contracts.length === 0" class="card mt-4">
      <div class="card-body">
        <div class="empty-message text-center py-4">
          <i class="fa fa-check-circle text-success display-4 mb-3"></i>
          <h4>没有待审核的合同</h4>
          <p class="text-muted">所有待审核合同都已处理完成</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'AuditContracts',
  setup() {
    const store = useStore()
    const router = useRouter()

    const loading = ref(true)
    const errorMessage = ref('')
    const contracts = ref([])
    const currentPage = ref(0)
    const pageSize = ref(10)
    const totalPages = ref(0)
    const totalCount = ref(0)
    const jumpPageNum = ref(1) // 跳转页码输入值

    // 用户信息
    const employeeId = ref(null)
    const employeePosition = ref(null)
    const isLegalSpecialist = ref(false)
    const isFinanceSpecialist = ref(false)

    // 跳转页码验证
    const isJumpValid = computed(() => {
      return Number.isInteger(jumpPageNum.value) &&
          jumpPageNum.value >= 1 &&
          jumpPageNum.value <= totalPages.value &&
          jumpPageNum.value !== currentPage.value + 1
    })

    // 返回员工控制台
    const goToDashboard = () => {
      router.push('/employee/dashboard')
    }

    // 获取待审核合同
    const fetchContracts = () => {
      loading.value = true
      errorMessage.value = ''

      // 检查用户信息是否完整
      if (!employeeId.value) {
        errorMessage.value = '用户信息加载中，请稍后...'
        loading.value = false
        return
      }

      // 确定审核类型
      const auditType = isLegalSpecialist.value ? 'legal' : 'finance'

      // 获取待审核合同
      axios.get(`/auth/contracts/pending-audit`, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': employeePosition.value
        },
        params: {
          page: currentPage.value,
          size: pageSize.value,
          type: auditType
        }
      })
          .then(response => {
            contracts.value = response.data.content || []
            totalPages.value = response.data.totalPages || 1
            totalCount.value = response.data.totalElements || 0
            // 同步当前页码到跳转输入框
            jumpPageNum.value = currentPage.value + 1
          })
          .catch(error => {
            console.error('获取待审核合同失败', error)
            errorMessage.value = error.response?.status === 403
                ? '您没有权限查看待审核合同'
                : '获取待审核合同失败，请稍后再试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 查看合同详情并开始审核
    const viewContract = (contractId) => {
      router.push(`/employee/audit-contract/${contractId}`)
    }

    // 分页操作
    const prevPage = () => {
      if (currentPage.value > 0) {
        currentPage.value--
        fetchContracts()
      }
    }

    const nextPage = () => {
      if (currentPage.value < totalPages.value - 1) {
        currentPage.value++
        fetchContracts()
      }
    }

    // 处理页码跳转
    const handleJump = () => {
      if (!isJumpValid.value) return
      // 转换为从0开始的索引
      currentPage.value = jumpPageNum.value - 1
      fetchContracts()
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    onMounted(() => {
      // 初始化用户信息
      employeeId.value = store.state.user?.id
      employeePosition.value = store.state.user?.position
      isLegalSpecialist.value = store.state.user?.position === 'LEGAL_SPECIALIST'
      isFinanceSpecialist.value = store.state.user?.position === 'FINANCE_SPECIALIST'

      // 监听用户信息变化
      watch([
        () => store.state.user?.id,
        () => store.state.user?.position
      ], () => {
        employeeId.value = store.state.user?.id
        employeePosition.value = store.state.user?.position
        isLegalSpecialist.value = store.state.user?.position === 'LEGAL_SPECIALIST'
        isFinanceSpecialist.value = store.state.user?.position === 'FINANCE_SPECIALIST'
        fetchContracts()
      })

      fetchContracts()
    })

    return {
      loading,
      errorMessage,
      contracts,
      currentPage,
      pageSize,
      totalPages,
      totalCount,
      jumpPageNum,
      isJumpValid,
      goToDashboard,
      viewContract,
      prevPage,
      nextPage,
      handleJump,
      formatDate,
      isLegalSpecialist,
      isFinanceSpecialist
    }
  }
}
</script>

<style scoped>
.header {
  background-color: #f8f9fa;
  padding: 15px;
  border-bottom: 1px solid #dee2e6;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  padding: 10px 15px;
  color: #721c24;
  background-color: #f8d7da;
  border-radius: 4px;
  margin: 15px 0;
  display: flex;
  align-items: center;
}

.card {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #dee2e6;
}

.card-header {
  border-radius: 8px 8px 0 0;
}

.contracts-table {
  margin-top: 15px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

/* 跳转控件样式 */
.page-jump {
  margin-left: 15px;
  padding-left: 15px;
  border-left: 1px solid #e9ecef;
}

.page-input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  text-align: center;
}

.page-input:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* 跳转按钮样式 */
.btn-jump {
  background-color: #17a2b8;
  color: #fff;
}

.btn-jump:hover {
  background-color: #138496;
}

.btn-jump:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.empty-message {
  padding: 30px 0;
}

.empty-message i {
  color: #adb5bd;
}

.empty-message h4 {
  color: #495057;
  margin-bottom: 10px;
}

.empty-message p {
  color: #6c757d;
  margin-bottom: 0;
}

/* 表格样式优化 */
.table {
  width: 100%;
  border-collapse: collapse;
}

.table th, .table td {
  padding: 0.75rem;
  vertical-align: middle;
  border-bottom: 1px solid #e5e7eb;
  word-break: break-word;
}

.table th {
  font-weight: 500;
  color: #4b5563;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 2px solid #e5e7eb;
}

.table tbody tr {
  vertical-align: middle;
}

/* 按钮样式优化 */
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0.375rem 0.75rem;
  font-size: 0.875rem;
  font-weight: 500;
  line-height: 1.5;
  border-radius: 0.25rem;
  transition: all 0.2s ease-in-out;
  border: 1px solid transparent;
  cursor: pointer;
}

.btn-primary {
  color: #fff;
  background-color: #007bff;
  border-color: #007bff;
}

.btn-primary:hover {
  background-color: #0069d9;
  border-color: #0062cc;
}

.btn-secondary {
  color: #fff;
  background-color: #6c757d;
  border-color: #6c757d;
}

.btn-secondary:hover {
  background-color: #5a6268;
  border-color: #545b62;
}

.btn-outline-secondary {
  color: #6c757d;
  background-color: transparent;
  border-color: #6c757d;
}

.btn-outline-secondary:hover {
  color: #fff;
  background-color: #6c757d;
  border-color: #6c757d;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .pagination {
    flex-direction: column;
    align-items: flex-start !important;
  }

  .pagination-controls {
    width: 100%;
    justify-content: space-between;
    margin-top: 10px;
  }

  .page-jump {
    margin-left: 0;
    padding-left: 0;
    border-left: none;
  }
}
</style>